<?php
session_start();

$jobDone = "nothing";

  function __autoload($class_name) {
      require_once ('../classes/' . $class_name . '.class.php');
  }

  include "../include/sitefunctions.php";
  include "../include/lobbyfunctions.php";

/* This will do three things...

1 - accept posted new messages, and save them into the database

2 - accept keep-alive messages; these also send any new messages to all users

3 - add new users to the online database

*/

  function outputXMLHeader() {
    header("Content-Type: text/xml; charset=ISO-8859-1");
    echo '<?xml version="1.0" encoding="UTF-8" ?>';
    echo '<xml>';
    return true;
  }

  function outputNormalHeader() {
    header("Content-Type: text/html; charset=ISO-8859-1");
  }

  $XMLHeader = false;
  $db = new DbConnection();
  
  if (isset($_GET['newmessage'])) {
    $user = $_GET['user'];
    $message = $_GET['message'];
    
    $posted = date('H:i:s');
    
    $sqlUsr = "SELECT * FROM lobbyusers WHERE username='$user'";
    $userResult = $db->dbSelect($sqlUsr);
    if ($userResult) {
      $userDetails = mysql_fetch_array($userResult);
      outputNormalHeader();
      if ($userDetails['username'] == $user) {
        $message = cleanText($message);
        $user = cleanText($user);
        
        postMessage($db, $user, $message, $posted);
          //$db->dbInsert("INSERT INTO lobby (`id`, `username`, `message`, `posted`) VALUES (NULL, '$user', '$message', '$posted')");
          //$db->dbUpdate("UPDATE lobbyusers SET `posts`=`posts`+1 WHERE `username`='$user';");
        echo '<span class="postDate">('. $posted .')</span> <em class="usernameem">'.$user.'</em>: '.$message;

        $jobDone = "newmessage";
      } else {
        echo '<span class="postDate">('. $posted .')</span> Unknown user, please login!';
      }
    }
  }
  
  if (isset($_GET['createGame'])) {
    
    
    
  }
  
  if (isset($_GET['joingame'])) {
    $toJoin = $_GET['joingame'];
    $user = $_GET['user'];
    $joinedGame = false;
    $failedReason = "";
    
    $sqlGames = "SELECT * FROM games WHERE id='".$toJoin."'";
    $gameResult = $db->dbSelect($sqlGames);
    // Get all the users:
    if ($gameResult) {
      $gameDetails = mysql_fetch_array($gameResult);
      if ($toJoin == $gameDetails['id']) {
        // found the game
        $playersInGame = 0;
        for ($count = 1; $count < 5; $count++) {
          $column = "player". $count;
          if ($gameDetails[$column] != "-") {
            $playersInGame ++;
          }
        }
        
        if ($playersInGame < $gameDetails['maxplayers']) {
          for ($count = 1; $count < 5; $count++) {
            $column = "player". $count;
            if ($gameDetails[$column] == "-") {
              $db->dbUpdate("UPDATE games SET ".$column."='".$user."' WHERE id='".$toJoin."'");
              $joinedGame = true;
              break;
            }
          }
        } else {
          $failedReason = "Game full";
        }
      } else {
        $failedReason = "Game id invalid";
      }
    } else {
      $failedReason = "Game id not found";
    }
    
    outputNormalHeader();
    if ($joinedGame == true) {
      $_SESSION['ingame'] = $toJoin;
      $_SESSION['host'] = false;
      echo "joined:".$_SESSION['ingame'];
      postMessage($db, "system", $_SESSION['username'] . " joined " . $gameDetails['name'] . "(".$_SESSION['ingame'].")", date('H:i:s'));
    } else {
      echo "failed:". $failedReason;
    }
  }
  
  if (isset($_GET['lobbypoll'])) {
    $XMLHeader = false;
    
    $user = $_GET['user'];
    
    $sqlUsr = "SELECT * FROM lobbyusers WHERE username='$user'";
    $userResult = $db->dbSelect($sqlUsr);
    if ($userResult) {
      $userDetails = mysql_fetch_array($userResult);
      if ($user == $userDetails['username']) {
        $lastRecveivedIndex = $userDetails['lastreceived'];
        
        // get an updated list of messages
        // filters out messages sent by the current user; since he'll see them anyway!
        $sqlMsg = "SELECT * FROM lobby WHERE id > '$lastRecveivedIndex' AND username !='$user' ORDER BY id DESC LIMIT 0, 5";
        $msgResult = $db->dbSelect($sqlMsg);
        if ($msgResult) {
          if ($XMLHeader == false) {
            $XMLHeader = outputXMLHeader();
          }
          $highestId = $lastRecveivedIndex;
          if (mysql_num_rows($msgResult) > 0) {
            echo "<lobbymessages>";
            while ($messageDetails = mysql_fetch_array($msgResult)) {
              if ($highestId < $messageDetails['id']) {
                $highestId = $messageDetails['id'];
              }
              echo "
                <message>
                  <posted>". $messageDetails['posted'] ."</posted>
                  <username>".$messageDetails['username']."</username>
                  <text>".$messageDetails['message']."</text>
                </message>";
            }
            echo '</lobbymessages>';
          }
          
          if ($lastRecveivedIndex < $highestId) {
            $db->dbUpdate("UPDATE lobbyusers SET `lastreceived`='$highestId' WHERE `username`='$user'");
          }
        }
        
        $sqlUsers = "SELECT * FROM lobbyusers WHERE `loggedon`='1' ORDER BY username DESC";
        $userResult = $db->dbSelect($sqlUsers);
        // Get all the users:
        if ($userResult) {
          if ($XMLHeader == false) {
            $XMLHeader = outputXMLHeader();
          }
          
          if (mysql_num_rows($userResult) > 0) {
            echo "<lobbyusers>";
            while ($userDetails = mysql_fetch_array($userResult)) {
              echo "
                <user>
                  <name>".$userDetails['username']."</name>
                </user>";
            }
            echo '</lobbyusers>';
          }
        }
        
        $sqlGames = "SELECT * FROM games ORDER BY name DESC";
        $gameResult = $db->dbSelect($sqlGames);
        // Get all the users:
        if ($gameResult) {
          if ($XMLHeader == false) {
            $XMLHeader = outputXMLHeader();
          }
          
          if (mysql_num_rows($gameResult) > 0) {
            echo "<lobbygames>";
            while ($gameDetails = mysql_fetch_array($gameResult)) {
              $playersInGame = 0;
              for ($count = 1; $count < 5; $count++) {
                $column = "player". $count;
                if ($gameDetails[$column] != "-") {
                  $playersInGame ++;
                }
              }
              
              if ($playersInGame == 0) {
                //delete the game
                $db->dbDelete("DELETE FROM games WHERE id='".$gameDetails['id']."'");
              } else {
                echo "
                  <game>
                    <id>".$gameDetails['id']."</id>
                    <name>".$gameDetails['name']."</name>
                    <player1>".$gameDetails['player1']."</player1>
                    <ingame>".$playersInGame."</ingame>
                    <maxplayers>".$gameDetails['maxplayers']."</maxplayers>
                    <map>".$gameDetails['map']."</map>
                    <inprogress>".$gameDetails['inprogress']."</inprogress>
                  </game>";
              }
            }
            echo '</lobbygames>';
            
          }
        }
        
        echo "</xml>";
      } else {
        // User not found...
      }
    } else {
      // Username not found, need a special case for this, though it should not happen
    }
  }
?>
